<template>
  <div class="article-detail-container">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else class="article-content csdn-style-article">
      <h1 class="article-title">{{ article && article.title }}</h1>
      
      <div class="article-meta">
        <div class="author-info">
          <el-avatar :src="article && article.user?.avatarUrl ? getAvatarUrl(article.user.avatarUrl) : (article && article.authorAvatar ? getAvatarUrl(article.authorAvatar) : defaultAvatar)" :size="40" @click="viewAuthor" />
          <div class="author-detail">
            <div class="author-name" @click="viewAuthor">{{ article && article.user?.nickname || article && article.authorName || '匿名用户' }}</div>
            <div class="publish-time">{{ formatDate(article && article.createTime) }}</div>
          </div>
        </div>
        
        <div class="article-tags">
          <el-tag 
            v-if="article && article.boardName" 
            type="primary" 
            effect="plain" 
            class="board-tag"
            @click="navigateToBoard"
          >
            {{ article.boardName }}
          </el-tag>
          
          <el-tag 
            v-for="tag in articleTags" 
            :key="tag" 
            class="article-tag"
            @click="navigateToTag(tag)"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>
      
      <!-- 使用高级Markdown渲染组件显示文章内容 -->
      <div class="article-main-content">
        <AdvancedMarkdown 
          v-if="article && article.content" 
          :text="article.content" 
          :showSource="false" 
          :showToc="true" 
          class="article-body-content"
        />
      </div>
      
      <div class="article-actions">
        <el-button 
          type="primary" 
          :icon="article && article.isLiked ? 'Star' : 'Star'" 
          :class="{ 'is-liked': article && article.isLiked }"
          @click="likeArticle"
        >
          {{ article && article.likeCount || 0 }} 赞
        </el-button>
        
        <el-button type="info" icon="Collection" @click="collectArticle">
          收藏
        </el-button>
        
        <el-button type="info" icon="Share" @click="shareArticle">
          分享
        </el-button>
        
        <!-- 编辑按钮 - 仅文章作者和管理员可见 --> 
        <el-button 
          v-if="canEditArticle" 
          type="warning" 
          icon="Edit" 
          @click="editArticle"
        >
          编辑
        </el-button>
        
        <!-- 删除按钮 - 仅文章作者和管理员可见 -->
        <el-button 
          v-if="canEditArticle" 
          type="danger" 
          icon="Delete" 
          @click="deleteArticle"
        >
          删除
        </el-button>
      </div>
      
      <!-- 评论区 -->
      <div class="comment-section">
        <h3 class="comment-title">评论 ({{ commentCount }})</h3>
        
        <!-- 评论表单 -->
        <div class="comment-form" v-if="isLoggedIn">
          <el-input
            v-model="commentContent"
            type="textarea"
            :rows="3"
            placeholder="发表你的评论..."
          />
          <el-button 
            type="primary" 
            class="comment-submit" 
            :loading="submitting"
            @click="submitComment"
          >
            发表评论
          </el-button>
        </div>
        <div v-else class="login-to-comment">
          <router-link to="/login">登录</router-link> 后发表评论
        </div>
        
        <!-- 评论列表 -->
        <div class="comment-list">
          <!-- 评论加载中 -->
          <div v-if="commentsLoading" class="comments-loading">
            <el-skeleton :rows="3" animated />
          </div>
          
          <!-- 暂无评论 -->
          <el-empty v-else-if="comments.length === 0" description="暂无评论" />
          
          <!-- 评论内容 -->
          <div v-else class="comment-items">
            <div 
              v-for="comment in comments" 
              :key="comment.id" 
              class="comment-item"
            >
              <div class="comment-user">
                <el-avatar :src="comment.user?.avatarUrl ? getAvatarUrl(comment.user.avatarUrl) : defaultAvatar" :size="32" @click="viewUser(comment.postUserId)" />
                <div class="comment-info">
                  <div class="comment-username" @click="viewUser(comment.postUserId)">
                    {{ comment.user?.nickname || '匿名用户' }}
                  </div>
                  <div class="comment-time">{{ formatDate(comment.createTime) }}</div>
                </div>
              </div>
              
              <div class="comment-content">{{ comment.content }}</div>
              
              <div class="comment-actions">
                <span @click="replyComment(comment)">回复</span>
                <span v-if="canDeleteComment(comment)" @click="handleDeleteComment(comment.id)">删除</span>
              </div>
            </div>
          </div>
          
          <!-- 分页 -->
          <el-pagination
            v-if="commentCount > 10"
            background
            layout="prev, pager, next"
            :total="commentCount"
            :page-size="10"
            @current-change="handleCommentPageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import config from '@/config'
import { CopyDocument } from '@element-plus/icons-vue'
import { MdEditor } from 'md-editor-v3'
import MarkdownPreview from '@/components/MarkdownPreview.vue'
import BasicMarkdown from '@/components/BasicMarkdown.vue'
import AdvancedMarkdown from '@/components/AdvancedMarkdown.vue'
import 'md-editor-v3/lib/style.css'

export default {
  name: 'ArticleDetail',
  
  components: {
    CopyDocument,
    MdEditor,
    MarkdownPreview,
    BasicMarkdown,
    AdvancedMarkdown
  },
  
  setup() {
    const store = useStore()
    const route = useRoute()
    const router = useRouter()
    
    const loading = ref(true)
    const article = ref({})
    const comments = ref([])
    const commentsLoading = ref(false)
    const commentContent = ref('')
    const submitting = ref(false)
    const commentCount = ref(0)
    const defaultAvatar = require('@/assets/default-avatar.png')
    
    // 头像URL处理
    const getAvatarUrl = (url) => {
      const result = config.getDirectAvatarUrl(url);
      return result;
    }
    
    // 图片URL处理
    const getImageUrl = (url) => {
      console.log('ArticleDetail 原始图片URL:', url);
      const result = config.getImageUrl(url);
      console.log('ArticleDetail 处理后图片URL:', result);
      return result;
    }
    
    const isLoggedIn = computed(() => store.getters['user/isLoggedIn'])
    const currentUserId = computed(() => store.getters['user/userId'] || null)
    const isAdmin = computed(() => store.getters['user/isAdmin'])
    
    // 判断是否可以编辑文章
    const canEditArticle = computed(() => {
      return isLoggedIn.value && 
             article.value && 
             (article.value.userId === currentUserId.value || isAdmin.value || article.value.own === true)
    })
    
    const articleTags = computed(() => {
      if (!article.value || !article.value.tags) return []
      return typeof article.value.tags === 'string'
        ? article.value.tags.split(',').filter(tag => tag.trim())
        : article.value.tags
    })
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '未知时间'
      try {
        const dateObj = new Date(date)
        if (isNaN(dateObj.getTime())) return '未知时间'
        return dateObj.toLocaleString()
      } catch (error) {
        return '未知时间'
      }
    }
    
    // 文章ID
    const articleId = computed(() => `article-detail-${route.params.id}`)
    
    // 加载文章详情
    const loadArticleDetail = async () => {
      loading.value = true
      const articleId = route.params.id
      
      try {
        const response = await api.article.getDetail(articleId)
        if (response && response.code === 0 && response.data) {
          // 确保article.content是字符串
          const data = response.data
          if (data.content && typeof data.content !== 'string') {
            console.warn('Article content is not a string:', typeof data.content)
            data.content = JSON.stringify(data.content)
          }
          
          if (!data.content) {
            data.content = '内容为空'
          }
          
          // 处理文章内容中的图片URL
          if (data.content) {
            // 仅做日志输出，实际处理在AdvancedMarkdown组件中进行
            console.log('文章内容中可能包含的图片数量:', (data.content.match(/!\[.*?\]\(.*?\)/g) || []).length)
          }
          
          article.value = data
          
        
          
          // 更新文章浏览数
          store.dispatch('article/updateArticleViewCount', articleId)
          
          // 加载评论
          loadComments()
        } else {
          // 处理获取文章失败的情况
          article.value = { title: '文章不存在或已被删除', content: '该文章可能已被作者删除或移动。' }
          ElMessage.error(response?.message || '获取文章详情失败')
        }
      } catch (error) {
        console.error('获取文章详情失败:', error)
        // 设置一个默认的文章对象，防止null错误
        article.value = { title: '加载失败', content: '获取文章详情失败，请稍后重试。' }
        ElMessage.error('获取文章详情失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
    
    // 加载评论
    const loadComments = async (page = 1) => {
      if (!article.value || !article.value.id) return
      
      commentsLoading.value = true
      const articleId = article.value.id
      
      try {
        const response = await api.comment.getUserCommentsByArticleId(articleId, { page, size: 10 })
        if (response && response.code === 0) {
          comments.value = response.data || []
          commentCount.value = response.total || comments.value.length || 0
        } else if (response && response.code === 1001) {
          // 未登录状态，静默处理，显示空评论列表
          comments.value = []
          commentCount.value = 0
        } else {
          // 其他错误才显示错误消息
          console.error('获取评论失败:', response)
          ElMessage.error(response?.message || '获取评论失败')
          comments.value = []
          commentCount.value = 0
        }
      } catch (error) {
        console.error('获取评论失败:', error)
        // 只在非认证错误时显示错误消息
        if (!error || error.code !== 1001) {
          ElMessage.error('获取评论失败，请稍后重试')
        }
        comments.value = []
        commentCount.value = 0
      } finally {
        commentsLoading.value = false
      }
    }
    
    // 查看作者主页
    const viewAuthor = () => {
      if (!article.value) return
      const userId = article.value.user?.id || article.value.userId
      if (!userId) return
      router.push(`/user/${userId}`)
    }
    
    // 查看用户主页
    const viewUser = (userId) => {
      router.push(`/user/${userId}`)
    }
    
    // 导航到板块
    const navigateToBoard = () => {
      if (!article.value || !article.value.boardId) return
      router.push(`/board/${article.value.boardId}`)
    }
    
    // 导航到标签
    const navigateToTag = (tag) => {
      if (!tag) return
      router.push(`/search?tag=${encodeURIComponent(tag)}`)
    }
    
    // 点赞文章
    const likeArticle = async () => {
      if (!isLoggedIn.value) {
        ElMessage.warning('请先登录')
        return
      }
      
      if (!article.value || !article.value.id) {
        ElMessage.error('文章不存在')
        return
      }
      
      try {
        // 如果已经点赞，则取消点赞
        const apiMethod = article.value.isLiked ? 
          api.article.cancelThumbsUp : api.article.thumbsUp
        
        const response = await apiMethod(article.value.id)
        
        if (response.code === 0) {
          article.value.isLiked = !article.value.isLiked
          
          // 更新点赞数
          if (article.value.isLiked) {
            article.value.likeCount = (article.value.likeCount || 0) + 1
          } else {
            article.value.likeCount = Math.max((article.value.likeCount || 0) - 1, 0)
          }
          
          ElMessage.success(article.value.isLiked ? '点赞成功' : '已取消点赞')
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('点赞操作失败', error)
        ElMessage.error('操作失败，请稍后重试')
      }
    }
    
    // 收藏文章
    const collectArticle = () => {
      if (!isLoggedIn.value) {
        ElMessage.warning('请先登录')
        return
      }
      
      if (!article.value || !article.value.id) {
        ElMessage.error('文章不存在')
        return
      }
      
      // TODO: 实现收藏功能
      ElMessage.success('收藏成功')
    }
    
    // 分享文章
    const shareArticle = () => {
      if (!article.value || !article.value.id) {
        ElMessage.error('文章不存在')
        return
      }
      
      // 获取当前页面URL
      const url = window.location.href
      
      // 复制URL到剪贴板
      navigator.clipboard.writeText(url)
        .then(() => {
          ElMessage.success('链接已复制到剪贴板')
        })
        .catch(() => {
          ElMessage.error('复制失败，请手动复制链接')
        })
    }
    
    // 编辑文章
    const editArticle = () => {
      if (!article.value || !article.value.id) {
        ElMessage.error('文章不存在')
        return
      }
      
      router.push(`/article/${article.value.id}/edit`)
    }
    
    // 删除文章
    const deleteArticle = () => {
      if (!article.value || !article.value.id) {
        ElMessage.error('文章不存在')
        return
      }
      
      ElMessageBox.confirm(
        '确定要删除这篇文章吗？此操作不可恢复。',
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await api.article.delete(article.value.id)
          
          if (response.code === 0) {
            ElMessage.success('文章已删除')
            router.push('/articles')
          } else {
            ElMessage.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除文章失败', error)
          ElMessage.error('删除失败，请稍后重试')
        }
      }).catch(() => {
        // 用户取消删除，不做任何操作
      })
    }
    
    // 提交评论
    const submitComment = async () => {
      if (!isLoggedIn.value) {
        ElMessage.warning('请先登录')
        return
      }
      
      if (!article.value || !article.value.id) {
        ElMessage.error('文章不存在')
        return
      }
      
      if (!commentContent.value.trim()) {
        ElMessage.warning('评论内容不能为空')
        return
      }
      
      submitting.value = true
      
      try {
        const response = await api.comment.create({
          articleId: article.value.id,
          content: commentContent.value.trim()
        })
        
        if (response.code === 0) {
          ElMessage.success('评论发表成功')
          commentContent.value = ''
          loadComments()
        } else {
          ElMessage.error(response.message || '评论发表失败')
        }
      } catch (error) {
        console.error('发表评论失败', error)
        ElMessage.error('评论发表失败，请稍后重试')
      } finally {
        submitting.value = false
      }
    }
    
    // 回复评论
    const replyComment = (comment) => {
      if (!isLoggedIn.value) {
        ElMessage.warning('请先登录')
        return
      }
      
      if (!comment) {
        return
      }
      
      // 设置评论框内容，@用户名
      commentContent.value = `@${comment.user?.nickname || '用户'} `
      
      // 滚动到评论框
      document.querySelector('.comment-form')?.scrollIntoView({ behavior: 'smooth' })
    }
    
    // 判断是否可以删除评论
    const canDeleteComment = (comment) => {
      if (!comment || !isLoggedIn.value) return false
      
      // 如果是评论作者或文章作者或管理员，可以删除评论
      return comment.postUserId === currentUserId.value || 
             article.value?.userId === currentUserId.value || 
             isAdmin.value
    }
    
    // 删除评论
    const handleDeleteComment = async (commentId) => {
      if (!commentId) {
        return
      }
      
      try {
        const confirmed = await ElMessageBox.confirm(
          '确定要删除此评论吗？此操作不可恢复。',
          '删除确认',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        if (confirmed) {
          const response = await api.comment.delete(commentId)
          
          if (response.code === 0) {
            ElMessage.success('评论已删除')
            loadComments()
          } else {
            ElMessage.error(response.message || '删除失败')
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除评论失败', error)
          ElMessage.error('删除失败，请稍后重试')
        }
      }
    }
    
    // 评论分页
    const handleCommentPageChange = (page) => {
      loadComments(page)
    }
    
    onMounted(() => {
      // 确保初始化文章对象
      article.value = { 
        title: '',
        content: '',
        authorName: '',
        createTime: '',
        likeCount: 0
      }
      
      // 加载文章详情
      loadArticleDetail()
    })
    
    return {
      loading,
      article,
      comments,
      commentsLoading,
      commentContent,
      submitting,
      commentCount,
      defaultAvatar,
      isLoggedIn,
      articleTags,
      canEditArticle,
      formatDate,
      viewAuthor,
      viewUser,
      navigateToBoard,
      navigateToTag,
      likeArticle,
      collectArticle,
      shareArticle,
      editArticle,
      deleteArticle,
      submitComment,
      replyComment,
      handleDeleteComment,
      canDeleteComment,
      handleCommentPageChange,
      articleId,
      getAvatarUrl,
      getImageUrl
    }
  }
}
</script>

<style scoped>
.article-detail-container {
  max-width: 100%;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f6f7;
  min-height: calc(100vh - 56px); /* 减去导航栏高度 */
}

.loading-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.article-content {
  max-width: 1000px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  padding: 30px;
  position: relative;
}

.article-title {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  margin-top: 0;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eaecef;
  line-height: 1.4;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-detail {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.author-name {
  font-size: 16px;
  font-weight: 600;
  color: #3b76c5;
  cursor: pointer;
  margin-bottom: 5px;
}

.author-name:hover {
  color: #1890ff;
}

.publish-time {
  font-size: 13px;
  color: #8c8c8c;
}

.article-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.board-tag, .article-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.board-tag:hover, .article-tag:hover {
  opacity: 0.8;
  transform: scale(1.05);
}

.article-main-content {
  line-height: 1.8;
  color: #303133;
  margin-bottom: 30px;
  overflow: hidden; /* 确保浮动的TOC不会影响布局 */
}

.article-body-content {
  font-size: 15px;
}

/* 专门为覆盖默认样式添加的类 */
.csdn-style-article {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji";
  color: #333;
}

/* 文章底部工具栏 */
.article-actions {
  display: flex;
  gap: 15px;
  margin: 30px 0;
  padding: 20px 0;
  border-top: 1px solid #eaecef;
}

.is-liked {
  color: #F56C6C;
  border-color: #F56C6C;
}

.comment-section {
  margin-top: 30px;
}

.comment-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
}

.comment-form {
  margin-bottom: 30px;
}

.comment-submit {
  margin-top: 10px;
  float: right;
}

.login-to-comment {
  margin-bottom: 30px;
  padding: 15px;
  background: #f2f6fc;
  border-radius: 4px;
  text-align: center;
}

.login-to-comment a {
  color: #409EFF;
  text-decoration: none;
}

.comments-loading {
  padding: 20px 0;
}

.comment-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.comment-user {
  display: flex;
  margin-bottom: 10px;
}

.comment-info {
  margin-left: 10px;
}

.comment-username {
  font-weight: 500;
  color: #303133;
  cursor: pointer;
}

.comment-username:hover {
  color: #409EFF;
}

.comment-time {
  font-size: 13px;
  color: #909399;
}

.comment-content {
  line-height: 1.6;
  color: #303133;
  margin: 10px 0;
}

.comment-actions {
  display: flex;
  gap: 15px;
  font-size: 13px;
  color: #909399;
}

.comment-actions span {
  cursor: pointer;
}

.comment-actions span:hover {
  color: #409EFF;
}

@media screen and (max-width: 768px) {
  .article-meta {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .article-tags {
    margin-top: 10px;
  }
  
  .article-actions {
    flex-wrap: wrap;
  }
}

/* Markdown编辑器自定义样式 */
.md-preview-custom {
  margin-top: 20px;
  width: 100% !important;
  min-height: 300px !important;
}

.md-preview-custom .md-editor-content {
  height: auto !important;
}
</style> 